

<template>
  <p>watch vs watchEffect</p>
  <p>{{ numberRef }}</p>
  <p>{{ name }} {{ age }}</p>
</template>

<script setup>
import { ref, reactive, toRefs, watch, watchEffect } from "vue";
const numberRef = ref(100);
const state = reactive({
  name: "wc",
  age: 18,
});
let { name, age } = toRefs(state);

// watch(
//   numberRef,
//   (newNumber, oldNumber) => {
//     console.log("ref watch", newNumber, oldNumber);
//   },
//   {
//     immediate: true,
//   }
// );
// setTimeout(() => {
//   numberRef.value = 200;
// }, 1500);

// watch(
//   () => state.age,
//   (newAge, oldAge) => {
//     console.log("state watch", newAge, oldAge);
//   },
//   {
//     immediate: true,
//     deep: true,
//   }
// );
// setTimeout(() => {
//   state.age = 25;
// }, 1500);

watchEffect(() => {
  // 初始化时，一定会执行一次（收集要监听的数据）
  console.log("hello watchEffect");
});
watchEffect(() => {
  // watchEffec会自动收集依赖，只有用取了相关的数据，才会重新执行。
  console.log("state.name", state.name);
});
watchEffect(() => {
  console.log("state.age", state.age);
  console.log("state.name", state.name);
});

setTimeout(() => {
  state.name = "xq";
}, 1500);
setTimeout(() => {
  state.age = 25;
}, 1500);
</script>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
